package zyf.jmidifile;

public final class JMidiUtils {
    public static int msToTicks(long ms, int tpq, int bpm, int beatUnit) {
        if (beatUnit <= 0 || bpm <= 0 || tpq <= 0 || ms <= 0) return 0;
        return (int) ((ms * tpq * bpm) / (15000.0 * beatUnit));
    }

    public static long ticksToMs(int ticks, int tpq, int bpm, int beatUnit) {
        if (ticks <= 0 || bpm <= 0 || tpq <= 0 || beatUnit <= 0) return 0;
        return (long) ((ticks * beatUnit * 15000.0) / (tpq * bpm));
    }


    /**
     * @param mpp      microseconds per quarter 的简写（3字节的固定长度)
     * @param beatUnit 以几分之小节为一拍
     * @return bpm beats per minutes
     */
    public static int mppToBpm(final byte[] mpp, int beatUnit) {
        if (mpp == null || mpp.length != 3 || beatUnit <= 0) return 0;
        int i = ((mpp[0] & 0xff) << 16) | ((mpp[1] & 0xff) << 8) | (mpp[2] & 0xff);
        return (int) ((60000000.0 / i) * (beatUnit / 4.0) + 0.5);
    }


    public static byte[] bpmToMpp(int bpm, int beatUnit) {
        if (bpm <= 0 || beatUnit <= 0) return null;
        byte[] mpp = new byte[3];
        int i = (int) (60000000.0 * beatUnit / 4.0 / bpm);
        mpp[2] = (byte) (i & 0xff);
        mpp[1] = (byte) ((i >> 8) & 0xff);
        mpp[0] = (byte) ((i >> 16) & 0xff);
        return mpp;
    }
}
